import { defineStore } from 'pinia';
import { user, errors, login, activity } from '@/api';
import qs from 'qs';
import { clearAuthToken } from '@/utils/userAuth';

interface userState {
	userInfo: { [key: string]: any };
	isLogin: boolean;
	isLibraryAdmin: boolean;
	adminInfo: {
		adminMobile: string;
		adminName: string;
		adminType: number;
		adminUser: number;
		id: number;
		loginPermission: number;
	} | null;
}
export const useUserStore = defineStore('user', {
	state: (): userState => ({
		isLogin: false,
		userInfo: {
			avatarUrl: '',
		},
		isLibraryAdmin: false,
		adminInfo: null,
	}),
	actions: {
		async init() {
			await this.getInfo();
		},
		async getInfo() {
			try {
				const params: any = {};
				const search = qs.parse(location.search.slice(1));
				if (search.ticket) {
					params.ticket = search.ticket;
				}
				const { data, ok } = await user.getUserInfo(params);

				if (!ok) {
					return;
				}

				const level = data.data && data.data.level ? data.data.level : 0;
				if (!level) {
					clearAuthToken();
					this.logout();
					return;
				}
				this.userInfo = data.data;
				this.getAdminType(data.data.id);
				this.isLogin = true;
			} catch (error) {
				errors(error);
			}
		},
		async logout() {
			const { ok, data } = await user.logout();
			if (!ok) {
				return;
			}
			login(data);
		},
		// 校验案例库权限管理员权限
		async getLibraryAdminPermission() {
			try {
				const { data, ok } = await activity.checkLibraryAdminPermission();
				if (!ok) {
					return;
				}
				this.isLibraryAdmin = data.data === 1;
			} catch (error) {
				errors(error);
			}
		},
		// 获取角色权限
		async getAdminType(userId: number) {
			if (!userId) {
				return;
			}
			try {
				const { data, ok } = await user.getAdminType(userId);
				if (!ok) {
					return;
				}
				this.adminInfo = data.data;
			} catch (error) {
				errors(error);
			}
		},
	},
});
